package com.party.jackclientandroid.ui_home.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.party.jackclientandroid.BaseActivity;
import com.party.jackclientandroid.BaseActivityTitle;
import com.party.jackclientandroid.R;
import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.api.OrderService;
import com.party.jackclientandroid.api.ShopService;
import com.party.jackclientandroid.base.BaseTextWatch;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.bean.CommonResult;
import com.party.jackclientandroid.bean.CouponBean;
import com.party.jackclientandroid.bean.DiscountPayBillBean;
import com.party.jackclientandroid.bean.PayResult;
import com.party.jackclientandroid.controller.PayController;
import com.party.jackclientandroid.utils.Utils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;


/**
 * 优惠买单
 */
public class DiscountPayBillActivityBackUp extends BaseActivityTitle {
    @BindView(R.id.whole_layout)
    LinearLayout whole_layout;
    @BindView(R.id.consume_sum_money_et)
    EditText all_money_et;
    @BindView(R.id.not_add_et)
    EditText not_add_et;
    @BindView(R.id.real_price_tv)
    TextView final_price_tv;
    @BindView(R.id.replace_money_coupon_ll)
    LinearLayout replace_money_coupon_ll;
    @BindView(R.id.pay_btn)
    Button pay_btn;
    @BindView(R.id.cut_line_view)
    View cut_line_view;
    @BindView(R.id.replace_money_coupon_list)
    LinearLayout replace_money_coupon_list;
    @BindView(R.id.discount_checkbox_ll)
    LinearLayout discount_checkbox_ll;
    @BindView(R.id.not_discount_ll)
    LinearLayout not_discount_ll;
    @BindView(R.id.discount_checkbox)
    CheckBox discount_checkbox;
    @BindView(R.id.discount_price)
    TextView discount_price;
    @BindView(R.id.num_tv)
    TextView num_tv;
    @BindView(R.id.is_discount_check)
    CheckBox is_discount_check;

    private String shopId, couponId;
    ShopService shopService;
    private DiscountPayBillBean disCoupon;
    private CouponBean selectCoupons;
    private int MY_RESULT_OK = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_discount_pay_bill);
        getIntentData(getIntent());
    }

    private void getIntentData(Intent intent) {
        shopId = intent.getStringExtra("shopId");
        couponId = intent.getStringExtra("couponId");
    }

    public interface PayCompleteListener {
        void payOk(BaseResult<PayResult> result);

        void payFail(String errorMessage);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == MY_RESULT_OK) {
            couponId = data.getStringExtra("couponId");
            refreshCoupon();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
        initLister();
    }


    private void initLister() {
        discount_checkbox.setOnCheckedChangeListener((CompoundButton buttonView, boolean isChecked) -> {
            refreshPayMoney();
        });
        discount_checkbox_ll.setOnClickListener((View v) -> {
            discount_checkbox.setChecked(!discount_checkbox.isChecked());//状态改变
        });
        replace_money_coupon_ll.setOnClickListener((View v) -> {
            Intent intent = new Intent(mActivity, DiscountPayBillCouponListActivity.class);
            intent.putParcelableArrayListExtra("couponList", disCoupon.getCoupons());
            startActivityForResult(intent, MY_RESULT_OK);
        });
        is_discount_check.setOnCheckedChangeListener((CompoundButton buttonView, boolean isChecked) -> {
            not_discount_ll.setVisibility(isChecked ? View.VISIBLE : View.GONE);
            refreshPayMoney();
        });
    }


    /**
     * 重新计算价格
     */
    private void refreshPayMoney() {
        totalPrice = all_money_et.getText().toString();
        noDiscountPrice = not_add_et.getText().toString();
        //不参与优惠如果被取消，设置不参与优惠为 0
        if (!is_discount_check.isChecked()) {
            noDiscountPrice = "0";
        }

        if (totalPrice.length() == 0) totalPrice = "0";
        if (noDiscountPrice.length() == 0) noDiscountPrice = "0";

        BigDecimal total = new BigDecimal(totalPrice);
        BigDecimal notJoin = new BigDecimal(noDiscountPrice);
        if (notJoin.doubleValue() > total.doubleValue()) {
            showToast("超过总价了");
            return;
        }


        //如果不使用优惠价  就计算代金券 价格
        if (!discount_checkbox.isChecked()) {
            discount_price.setText("优惠价格 ¥ 0");
            BigDecimal totalDisCouponPrice = new BigDecimal(0);
            if (selectCoupons != null) {
                replace_money_coupon_list.setVisibility(View.VISIBLE);
                BigDecimal originalPrice = new BigDecimal(selectCoupons.getOriginalPrice());
                totalDisCouponPrice = originalPrice.multiply(new BigDecimal(num_tv.getText().toString()));
            }
            total = total.subtract(notJoin).subtract(totalDisCouponPrice);
        } else {//使用折扣，计算折扣的价格
            BigDecimal dis = new BigDecimal(1).subtract(new BigDecimal(disCoupon.getDiscount()));
            replace_money_coupon_list.setVisibility(View.GONE);
            BigDecimal discountPrice = total.subtract(notJoin).multiply(dis);
            if (total.doubleValue() > 0) {
                discount_price.setText("优惠价格 ¥ -" + discountPrice);
            }
            total = total.subtract(discountPrice);
        }
        if (total.doubleValue() < 0) {
            finalPrice = notJoin.setScale(2, RoundingMode.HALF_DOWN).toString();
        } else {
            finalPrice = total.add(notJoin).setScale(2, RoundingMode.HALF_DOWN).toString();
        }

        orderId = null;
        final_price_tv.setText(finalPrice);
    }

    private void initData() {
        if (disCoupon == null) {
            shopService = new ShopService(this);
            addDisposableIoMain(shopService.getDiscountPayBill(shopId), new DefaultConsumer<DiscountPayBillBean>(mApplication) {
                @Override
                public void operateSuccess(BaseResult<DiscountPayBillBean> baseBean) {
                    disCoupon = baseBean.getData();
                    BigDecimal discount = new BigDecimal(disCoupon.getDiscount());
                    if (discount.floatValue() >= 1) {
                        not_discount_ll.setVisibility(View.GONE);
                        discount_checkbox_ll.setVisibility(View.GONE);
                    }
                    discount_checkbox.setText("首单" + Utils.clearZero(discount.multiply(new BigDecimal(10))) + "折");
                    setMiddleText(disCoupon.getShopName());
                    refreshCoupon();
                }
            });
        }


        all_money_et.addTextChangedListener(new BaseTextWatch() {
            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().startsWith(".")) {
                    all_money_et.setText("");
                    return;
                }
                refreshPayMoney();
            }
        });

        not_add_et.addTextChangedListener(new BaseTextWatch() {
            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().startsWith(".")) {
                    not_add_et.setText("");
                    return;
                }
                refreshPayMoney();

            }
        });
    }

    private void refreshCoupon() {
        if (couponId != null && disCoupon != null && disCoupon.getCoupons() != null) {
            replace_money_coupon_list.setVisibility(View.VISIBLE);
            ArrayList<CouponBean> coupons = disCoupon.getCoupons();
            for (int i = 0; i < coupons.size(); i++) {
                if (couponId.equals(coupons.get(i).getId() + "")) {
                    selectCoupons = coupons.get(i);
                    discount_checkbox.setChecked(false);
                    TextView viewById = replace_money_coupon_list.findViewById(R.id.coupon_title_tv);
                    viewById.setText(selectCoupons.getItemName());
                    num_tv.setText(selectCoupons.getCount() + "");
                    break;
                }
            }
        }
        refreshPayMoney();
    }


    public void optionCount(View view) {
        int count = Integer.parseInt(num_tv.getText().toString());
        switch (view.getId()) {
            case R.id.reduce_iv:
                count = count - 1;
                if (count < 1) count = 1;
                num_tv.setText(count + "");
                break;
            case R.id.add_iv:
                count = count + 1;
                if (count > selectCoupons.getCount()) count = selectCoupons.getCount();
                num_tv.setText(count + "");
                break;
        }
        refreshPayMoney();
    }

    PayController walletController;
    private String orderId;


    private String totalPrice, noDiscountPrice, finalPrice;

    public void startPay(View v) {

        walletController = new PayController((BaseActivity) mActivity, v);
        if (discount_checkbox.isChecked() && (finalPrice == null || Double.parseDouble(finalPrice) == 0)) {
            showToast("请输入金额");
            return;
        }
        if ((finalPrice == null || Double.parseDouble(finalPrice) == 0) && !discount_checkbox.isChecked() && couponId == null) {
            showToast("请输入金额");
            return;
        }
        if (!discount_checkbox.isChecked() && selectCoupons != null) {
            walletController.setPayTipTitle("消费：" + selectCoupons.getItemName() + " " + selectCoupons.getCount() + "张");
        }

        walletController.showPayMethod(finalPrice, orderId, (View vv) -> {
            Map<String, String> data = new HashMap<>();
            data.put("token", mApplication.getToken());
            data.put("totalPrice", totalPrice);
            data.put("finalPrice", finalPrice);
            data.put("shopId", shopId + "");
            data.put("isDiscount", discount_checkbox.isChecked() == true ? "1" : "0");
            data.put("noDiscountPrice", noDiscountPrice);
            data.put("couponNum", num_tv.getText().toString());
            data.put("couponId", couponId == null ? "0" : couponId);
            data.put("userPhone", mApplication.getUser().getPhone());
            OrderService orderService = new OrderService((BaseActivity) mActivity);

            addDisposableIoMain(orderService.addDiscountOrder(data), new DefaultConsumer<CommonResult>(mApplication) {
                @Override
                public void operateSuccess(BaseResult<CommonResult> result) {
                    orderId = result.getData().getId() + "";
                    walletController.pay(orderId);
                }
            });
        });

        walletController.setInputPassFinish(null);
    }


}
